package com.actionpals.managers
{
	import com.actionpals.display.IPopUpable;
	import com.actionpals.events.PopUpEvent;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.geom.Point;
	
	public class PopUpManager
	{
		public static function addPopUp( popUp:IPopUpable, parent:DisplayObjectContainer, modal:Boolean=true ):void
		{
			popUp.owner = parent;
			popUp.owner.dispatchEvent( new PopUpEvent( PopUpEvent.OPEN, true, false, popUp ) );
			popUp.isPopUp = true;
			
			var ownerGlobalPoint:Point = popUp.owner.localToGlobal( new Point( 0, 0 ) );
			popUp.x = ownerGlobalPoint.x + ( popUp.owner.width - popUp.width )/2;
			popUp.y = ownerGlobalPoint.y + ( popUp.owner.height - popUp.height )/2;
			
			var xDiff:Number = ( popUp.x + popUp.width ) - popUp.owner.stage.width;
			var yDiff:Number = ( popUp.y + popUp.height ) - popUp.owner.stage.height;
			
			popUp.x = ( xDiff > 0 ) ? ( popUp.x - xDiff ) : ( popUp.x < 0 ) ? 0 : popUp.x;
			popUp.y = ( yDiff > 0 ) ? ( popUp.y - yDiff ) : ( popUp.y < 0 ) ? 0 : popUp.y;
			
			popUp.owner.stage.addChild( DisplayObject( popUp ) );
		}
		
		public static function centerPopUp( popUp:IPopUpable ):void
		{
			var ownerGlobalPoint:Point = popUp.owner.stage.localToGlobal( new Point( 0, 0 ) );
			popUp.x = ownerGlobalPoint.x + ( popUp.owner.stage.width - popUp.width )/2;
			popUp.y = ownerGlobalPoint.y + ( popUp.owner.stage.height - popUp.height )/2;
		}
		
		public static function createPopUp( parent:DisplayObjectContainer, className:Class, modal:Boolean=true ):IPopUpable
		{
			var popUp:IPopUpable = new className();
			addPopUp( popUp, parent, modal );
			return popUp;
		}
		
		public static function removePopUp( popUp:IPopUpable ):void
		{
			popUp.owner.dispatchEvent( new PopUpEvent( PopUpEvent.CLOSE, true, false, popUp ) );
			popUp.owner.stage.removeChild( DisplayObject( popUp ) );
			popUp.isPopUp = false;
		}
	}
}